/**
 * Created by JLB1 on 2017/2/7.
 */

import React, {Component, PropTypes} from "react";
import ReactDOM from "react-dom";
import Clipboard from "clipboard";
import wx from "wx";
import AJAX from "../../lib/ajax";
import Tools from "../../lib/tools";
import Dialog from "../MyPackage/components/Dialog";
import Axios from "axios";
require('es6-promise').polyfill();
import weixinShare from "../../lib/weixinShare";

require('../../lib/rem');
require('../../styles/common.less');
require('../../styles/lux.less');
require('../../styles/resetWeui.less');

const id = Tools.getParams().id;
class OpenBoxSuccess extends Component {
    constructor(props) {
        super(props);
        this.state = {
            time60: 60,     //60s倒计时
            isTime60Over: false,     // 60s倒计时结束
            btnStateText: '再次开箱（60秒内有效）',
            time: 10,//10秒倒计时
            isContact: false,//是否联系客服
            isTimeOver: false,//10s倒计时结束
            isShowDetail: false,//是否展示收费详情
            data: {
                addr: '',
                code: '',
                settle_amount: '',
                balance: '',
            },
            isSuccess: true,
            isLoading: true,
            rule: ''
        };
        this.setTime = this.setTime.bind(this);
        this.setTime60 = this.setTime60.bind(this);     //60秒倒计时
        this.openBoxAgain = this.openBoxAgain.bind(this);
        this.searchOpenFinal = this.searchOpenFinal.bind(this);
        this.showTip = this.showTip.bind(this);
        this.handleStatLine = this.handleStatLine.bind(this);
        this.pickup_check = this.pickup_check.bind(this)
        this.putInClipboard = this.putInClipboard.bind(this)    //放入粘贴板
        this.handleSwitchDetail = this.handleSwitchDetail.bind(this)    //展开收起收费明细
    }

    componentWillMount() {
        weixinShare.hideAll()
        // AJAX.request("order_price_rule", {order_id: id}, (data) => {
        //     if (data.code === 0) {
        //         const dataBody = data.body || {};
        //         this.setState({
        //             rule: dataBody.rule_desc
        //         })
        //     }
        // });
        // //查询开箱指令
        // this.searchOpenFinal()
    }


    //10秒倒计时
    setTime() {
        if (this.state.time === 1) {
            this.setState({
                time: 10,
                btnStateText: '再次开箱（60秒内有效）',
                isTimeOver: true,
            });
            clearInterval(this.timer);//清空定时器
            return
        } else {
            this.setState({
                time: this.state.time -= 1,
                btnStateText: '箱门已打开(' + this.state.time + 's)秒后可再次点击',
            })
        }
    }

    //60秒倒计时
    setTime60() {
        if (this.state.time60 === 1) {
            this.setState({
                time60: 60,
                isTime60Over: true,
            });
            this.putInClipboard();
            clearInterval(this.timer60);//清空定时器
            return
        } else {
            this.setState({
                time60: this.state.time60 -= 1,
            })
        }
    }

    //放入粘贴板
    putInClipboard() {
        var _this = this;
        // console.log("_this.refs.contactService: ",_this.refs.contactService)
        var clipboard = new Clipboard(_this.refs.contactService, {
            // 点击copy按钮，直接通过text直接返回复印的内容
            text: function () {
                return '这里是copy内容';
            }
        });

        clipboard.on('success', function (e) {
            console.log(e);
        });

        clipboard.on('error', function (e) {
            console.log(e);
        });
    }

    //查询开箱指令
    searchOpenFinal() {
        const _this = this;
        let intervalTimes = 0;
        this.findFinel = setInterval(function () {
            intervalTimes++;
            if (intervalTimes >= 4) {
                clearInterval(_this.findFinel);
                return
            }
            _this.pickup_check()
        }, 2000);


    }

    pickup_check() {
        const _this = this;
        // AJAX.request("pickup_check", {order_id: id}, (data1) => {
        //     if (data1.code === 0) {
        //         //查询详情
        //         this.setState({
        //             isSuccess: data1.body.is_pickup,
        //         });
        //         setTimeout(function () {
        //             AJAX.request("order_detail", {order_id: id}, (data) => {
        //                 if (data.code === 0) {
        //                     const dataBody = data.body || {};
        //                     const storage_info = dataBody.storage_info || {};
        //                     let copyData = {
        //                         type: storage_info.type,
        //                         addr: storage_info.addr,
        //                         code: storage_info.code,
        //                         settle_amount: (dataBody.settle_amount / 100).toFixed(2),
        //                         balance: (dataBody.balance / 100).toFixed(2),
        //                     };
        //                     _this.setState({
        //                         data: copyData,
        //                         isLoading: false
        //                     })
        //                 }
        //             });
        //         }, 1000);
        //         //跳回首页
        //         if (data1.body.is_pickup) {
        //             clearInterval(_this.findFinel);
        //             _this.gotohome = setTimeout(function () {
        //                 location.href = './PickUp'
        //             }, 5000)
        //         }
        //     }
        // })
    }

    componentDidMount() {
        //埋点 百度统计
        Axios.get(`/api/getBaiduId`, {}).then(function (response) {
            const data = response.data || {};
            if (data.code === 0) {
                var BAIDU_TONGJI_ID = data.msg;
                var hm = document.createElement("script");
                hm.src = "https://hm.baidu.com/hm.js?" + BAIDU_TONGJI_ID;
                var s = document.getElementsByTagName("script")[0];
                s.parentNode.insertBefore(hm, s);
                // hm.onload = ()=> {
                //     var _hmt = window._hmt || [];
                //     _hmt.push(["_trackEvent", "page", "view", '']);
                // }
            }
        }).catch(function (error) {
            console.log(error)
        });

        this.setState({
            isLoading: false
        })

        //    开启60秒倒计时
        this.timer60 = setInterval(this.setTime60, 1000);

        //    获取微信权限，为关闭窗口请求做准备
        AJAX.request("get_signature", {
            full_url: window.location.href
        }, (data) => {
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: data.body.appid, // 必填，公众号的唯一标识
                timestamp: data.body.timestamp, // 必填，生成签名的时间戳
                nonceStr: data.body.noncestr, // 必填，生成签名的随机串
                signature: data.body.signature,// 必填，签名，见附录1
                jsApiList: ["closeWindow"] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
            })
        })
    }

    //开箱失败再次开箱
    openBoxAgain(e) {
        e.preventDefault();
        //开始倒计时
        this.timer = setInterval(this.setTime, 1000);
        // const _this = this;
        // AJAX.request("pickup_quick", {order_id: id}, (data) => {
        //     if (data.code === 0) {
        //         Toast.loading({
        //             content: "正在开箱中..."
        //         });
        //         setTimeout(()=> {
        //             _this.searchOpenFinal()
        //         }, 1000);
        //     }
        // })
    }

    showTip() {
        const content = this.state.rule || '';
        Dialog.info({
            title: "",
            content: content,
            okText: "确认",
            onOK: ()=> {
            }
        })
    }

    //展开收起收费明细
    handleSwitchDetail() {
        var _this = this;
        this.setState({
            isShowDetail: !_this.state.isShowDetail
        })
    }


    // 联系客服锚点
    handleStatLine() {
        var _this = this;
        //放入粘贴板
        // this.putInClipboard();
        Dialog.confirm({
            title: "",
            content: "内容已放入粘贴板",
            okText: "确认",
            cancelText: "取消",
            onOK: ()=> {
                //关闭窗口
                wx.closeWindow();
            },
            onCancel: ()=> {

            }
        })

        AJAX.request("stat_hotline", {}, (data) => {

        })
    }


    //清空定时器
    componentWillUnmount() {
        clearTimeout(this.gotohome);
        clearInterval(this.findFinel);
        clearInterval(this.timer);      //10秒定时
        clearInterval(this.timer);      //60秒定时
    }


    render() {

        const opanfainal = this.state.isLoading ? <span/> :
            <div>
                <div className="openBox">
                    <div className="openMain">
                        <div>
                            {
                                this.state.isSuccess ? <i className="iconfont icon-duigou OpenSuccessIcon"/> :
                                    <i className="iconfont icon-iconfontcolor93 OpenErrorIcon"/>
                            }
                        </div>
                        <div>
                            <p className="info">{this.state.isSuccess ? '箱门已打开' : '箱门打开失败'}</p>
                        </div>
                    </div>
                </div>
                <div className="expressDetailBox">
                    <div className="expressDetailItem">
                        <p className="expressDetail_title">存放位置：</p>
                        <p className="expressDetail_info">{this.state.data.addr}</p>
                    </div>
                    <div className="expressDetailItem beforeLine">
                        <p className="expressDetail_title">柜体编号：</p>
                        <p className="expressDetail_info">{this.state.data.code}</p>
                    </div>
                    <div className="expressDetailItem beforeLine">
                        <p className="expressDetail_title">取件费用：</p>
                        <p className="expressDetail_info"><span>{this.state.data.settle_amount}元</span></p>
                        <p className="detailBox" onClick={this.handleSwitchDetail}>费用明细<i
                            className={this.state.isShowDetail ? "iconfont icon-shousuo1 help" : "iconfont icon-shousuo help"}/>
                        </p>
                    </div>
                    {this.state.isShowDetail &&
                    <div className="expressDetailItem colorG">
                        <p className="expressDetail_title">基础费用：</p>
                        <p className="expressDetail_info">{this.state.data.balance}元 </p>
                    </div>
                    }
                    {this.state.isShowDetail &&
                    <div className="expressDetailItem colorG">
                        <p className="expressDetail_title">延期费用：</p>
                        <p className="expressDetail_info">{this.state.data.balance}元 </p>
                        <p className="helpBox" onClick={this.showTip}><i
                            className="iconfont icon-wen help"/>
                        </p>
                    </div>
                    }
                    <div className="expressDetailItem beforeLine">
                        <p className="expressDetail_title">当前余额：</p>
                        <p className="expressDetail_info">{this.state.data.balance}元 </p>
                    </div>
                </div>
                {
                    this.state.isSuccess ?

                        <div className="handleBtnGroup">
                            {this.state.isTime60Over ?
                                <a ref="contactService" onClick={this.handleStatLine} href="javascript:;"
                                   className="weui-btn weui-btn_white textGray">联系客服</a>
                                : <a href="javascript:;" onClick={this.openBoxAgain}
                                     className="weui-btn weui-btn_yellow">{this.state.btnStateText}</a>}

                            <a href="./PickUp"
                               className="weui-btn weui-btn_white textGray">继续取下一件</a>
                        </div>

                        :
                        <div className="handleBtnGroup">
                            <a href="javascript:;" onClick={this.openBoxAgain}
                               className="weui-btn weui-btn_yellow">确认开箱</a>
                            <a onClick={this.handleStatLine} href="tel:400-0052708"
                               className="weui-btn weui-btn_white textGray">联系客服</a>
                        </div>

                }

            </div>;
        return opanfainal
    }
}
ReactDOM.render(<OpenBoxSuccess />, document.getElementById('app'));
if (module.hot) {
    module.hot.accept();
}

